package com.demo.seckill.common.aop;

import com.google.common.util.concurrent.RateLimiter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author libo
 * @ClassName LimitAspect
 * @Description: 限流AOP
 * @date 2018/11/29 17:06
 */
@Component
@Scope
@Aspect
public class LimitAspect {
    //没秒只发出5个令牌，此处是单线程的限流，内部采用令牌桶算法实现
    public static RateLimiter rateLimiter = RateLimiter.create(5.0);

    //Service层切点  限流
    @Pointcut("@annotation(com.demo.seckill.common.aop.ServiceLock)")
    public void ServiceAspect() {

    }

    @Around("ServiceAspect()")
    public Object around(ProceedingJoinPoint joinPoint) {
        Boolean flag = rateLimiter.tryAcquire();
        Object o = null;
        if (flag) {
            try {
                o = joinPoint.proceed();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
        return o;
    }
}